<?php

/*
 * eWAY Payments Plugin Class
 */

class RM_Plugin_eWAYpayments extends RM_Payments_Plugin {

    /**
     * distination for posting the payment data
     * @var sting
     */

    private $_ipnLog = false; // logging enabled

    /**
     * Public constructor
     */
    public function __construct() {
        $this->name = 'eWAYpayments';
        $this->_ipnLogFile = RM_Environment::getConnector()->getCorePath() . DIRECTORY_SEPARATOR . 'userdata' . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR . 'eWAYpayments_log.txt';
    }

    /**
     * collects the payment data and sends to Authrize.net
     */
    public function Process($bookingRef, $ccArray, $userData) {

        if (empty($ccArray) || empty($userData))
            return false;
        $settingsObj = new RM_eWAYpayments();
        $settings = $settingsObj->getSettings()->current()->toArray();

        $eway = new RM_eWAYpayments_Service();

        if (!$eway) return false;
        // preauth_mode

	$eway->setTransactionData("TotalAmount", $ccArray['x_amount']); //mandatory field
	$eway->setTransactionData("CustomerFirstName", $userData['first_name']);
	$eway->setTransactionData("CustomerLastName", $userData['last_name']);
	$eway->setTransactionData("CustomerEmail", $userData['email']);
	$eway->setTransactionData("CustomerAddress", $userData['address']);
	$eway->setTransactionData("CustomerPostcode", $userData['zip']);
	$eway->setTransactionData("CustomerInvoiceDescription", $ccArray['x_description']);
	$eway->setTransactionData("CustomerInvoiceRef", $userData['customerInvoiceRef']);
	$eway->setTransactionData("CardHoldersName", $userData['first_name'] . " " . $userData['last_name']); //mandatory field
	$eway->setTransactionData("CardNumber", $ccArray['x_card_num']); //mandatory field
	$eway->setTransactionData("CardExpiryMonth", $ccArray['x_exp_date_month']); //mandatory field
	$eway->setTransactionData("CardExpiryYear", $ccArray['x_exp_date_year']); //mandatory field
	$eway->setTransactionData("TrxnNumber", $settings['ewayCustomerID']);
	$eway->setTransactionData("Option1", "");
	$eway->setTransactionData("Option2", "");
	$eway->setTransactionData("Option3", "");

	//for REAL_TIME_CVN
	$eway->setTransactionData("CVN", $ccArray['x_card_code']);

	//for GEO_IP_ANTI_FRAUD
	$eway->setTransactionData("CustomerIPAddress", $eway->getVisitorIP()); //mandatory field when using Geo-IP Anti-Fraud
	$eway->setTransactionData("CustomerBillingCountry", "AU"); //mandatory field when using Geo-IP Anti-Fraud


	//special preferences for php Curl
	$eway->setCurlPreferences(CURLOPT_SSL_VERIFYPEER, 0);  //pass a long that is set to a zero value to stop curl from verifying the peer's certificate
	//$eway->setCurlPreferences(CURLOPT_CAINFO, "/usr/share/ssl/certs/my.cert.crt"); //Pass a filename of a file holding one or more certificates to verify the peer with. This only makes sense when used in combination with the CURLOPT_SSL_VERIFYPEER option.
	//$eway->setCurlPreferences(CURLOPT_CAPATH, "/usr/share/ssl/certs/my.cert.path");
	//$eway->setCurlPreferences(CURLOPT_PROXYTYPE, CURLPROXY_HTTP); //use CURL proxy, for example godaddy.com hosting requires it
	//$eway->setCurlPreferences(CURLOPT_PROXY, "http://proxy.shr.secureserver.net:3128"); //use CURL proxy, for example godaddy.com hosting requires it

	$ewayResponseFields = $eway->doPayment($settings['ewayCustomerID'], $settings['test_mode'],$settings['preauth_mode'], $settings['storedpaymentsURL']);

        $responseData = false;
        $this->_logResults("------ Transaction Started ------");
       
	if($ewayResponseFields["EWAYTRXNSTATUS"]=="False"){
		$this->_logResults("Transaction Error: " . $ewayResponseFields["EWAYTRXNERROR"] . "<br>\n");
		foreach($ewayResponseFields as $key => $value)
                    $this->_logResults("\n<br>\$ewayResponseFields[\"$key\"] = $value");
		//header("Location: trasnactionerrorpage.php");
		//exit();
	}else if($ewayResponseFields["EWAYTRXNSTATUS"]=="True"){
		$this->_logResults("Transaction Success: " . $ewayResponseFields["EWAYTRXNERROR"]  . "<br>\n");
		foreach($ewayResponseFields as $key => $value){
			$this->_logResults("\n<br>\$ewayResponseFields[\"$key\"] = $value");
                        $responseData[$key] = $value;
                }
		//header("Location: trasnactionsuccess.php");
		//exit();
	}

        $this->_logResults("------ Transaction Ended ------");

        return $responseData;
    }

    /**
     * We don't need to present this plugins under admin tree menu 'Plugins', only on Config leaf
     * 
     * @return null
     */
    public function getNode() {
        return null;
    }


    /**
     * used to log results to the ipn log file so we can see whats happening
     *
     * @param boolean $success if this is a successful or fail log
     */
    private function _logResults($msg) {
        if (!$this->_ipnLog)
            return;  // is logging turned off?
        // Timestamp
        $text = '[' . date('m/d/Y g:i A') . '] - ';
        $text .= $msg;

        // Write to log
        $fp = fopen($this->_ipnLogFile, 'a');
        fwrite($fp, $text . "\n\n");
        fclose($fp);  // close file
    }

    //public function beginTransaction($value, $reservationID, $description, $successUrl, $cancelUrl, $callbackClassName){}
}